package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"starry_sky/internal/config"
	"starry_sky/internal/core"
	"starry_sky/internal/tools/logger"
	"strings"
)

func GetSystemLogFileList(c *gin.Context) {
	files, err := os.ReadDir(config.LogConfig.SystemLogConfig.Path)
	if logger.HasError(err, "打开文件夹异常") {
		c.JSON(http.StatusInternalServerError, core.Err.WithMsg("系统日志文件夹打开异常"))
	} else {
		var fileNameList []map[string]string
		for _, file := range files {
			returnMap := make(map[string]string)
			returnMap["fileName"] = strings.Split(file.Name(), ".")[0]
			fileNameList = append(fileNameList, returnMap)
		}
		c.JSON(http.StatusOK, core.OK.WithData(fileNameList))
	}
}

type DownloadSystemLogFileRequest struct {
	FileName string `json:"fileName"`
}

func DownloadSystemLogFile(c *gin.Context) {
	var parameter DownloadSystemLogFileRequest
	err := c.ShouldBindJSON(&parameter)
	if logger.HasError(err) {
		c.JSON(http.StatusInternalServerError, core.Err.WithMsg("接受参数错误"))
		return
	}
	c.File(config.LogConfig.SystemLogConfig.Path + "/" + parameter.FileName + ".log")
}
